/**
 * 登录界面
 */
var LoginBoard = Board.extend({
    /**
     * ip列表
     * @type {Array}
     * @private
     */
    _ipList: [],
    _ccsFileName: res.LoginBoard_json,
    initBoard: function () {
        playMusic('bgMusic');
        if (!cc.sys.isNative) {
            window.curVersion = '9.3.0';
        }
        // gameData.players = [];
        var isGuest = !cc.sys.isNative || window.inReview || window.inBanShu;
        safeVisible(this._nodeList['root.unit_LiaoBeLoginBtnUnit'], false);
        safeVisible(this._nodeList['root.unit_WeChatLoginBtnUnit'], !isGuest);
        safeVisible(this._nodeList['root.unit_XianLiaoLoginBtnUnit'], false);
        safeVisible(this._nodeList['root.unit_GuestLoginBtnUnit'], isGuest);
        if (this._nodeList['root.version']) this._nodeList['root.version'].setString('v:' + window.curVersion);
        if (this._nodeList['root.xieyi']) this._nodeList['root.xieyi'].setVisible(!window.inReview);
        if (!window.inReview && window.fristIn) {
            //showWindow('MianZeWindow');
        }

        if (this._nodeList['root.version']) this._nodeList['root.version'].setVisible(!window.inBanShu);
        if (this._nodeList['root.xieyi']) this._nodeList['root.xieyi'].setVisible(!window.inBanShu);

        if(!window.sdkInited){
            window.sdkInited = true;
            this._initSdk();
        }
        this._clearSub();

        //var meizi = playSpine(res.sp_meizi_json, 'animation', true);
        //meizi.setPosition(cc.p(1560 / 2+35,0));
        //this._nodeList['root.bg'].addChild(meizi);
        /*
        if(cc.sys.isNative){
            for(var i = 1;i<4;i++){
                var lizi = cc.ParticleSystem.create(login.res['huaihua_huaban'+ i +'_plist']);
                lizi.setPosition(cc.p(cc.winSize.width + 100,cc.winSize.height + 100));
                this.addChild(lizi);
            }
        }
         */
    },
    onEnterTransitionDidFinish: function () {
        Board.prototype.onEnterTransitionDidFinish.call(this);
        eventManager.dispatchEvent(EventKey.QuickLogin);
    },
    _clearSub:function () {
        // if(window.nativeVersion<'6.0.0'){
        //     var isClearSub =  cc.sys.localStorage.getItem('isClearSub');
        //     if(window.curVersion < '5.1.4.9' && !isClearSub){
        //         cc.sys.localStorage.removeItem('sub-version');
        //         cc.sys.localStorage.setItem('isClearSub',true);
        //     }
        // }
    },
    /**
     * 初始化sdk
     * @private
     */
    _initSdk: function () {
        DeviceUtil.regBakBtn();
        if(window.nativeVersion >= app.framework_version){
            //Sdk.registerQQ();
            Sdk.registerWeChat();
            Sdk.registerMagicWindow();
            Sdk.registerDingTalk();
            Sdk.registerLiaoBe();
            Sdk.registerXianLiao();
            Sdk.registerBugly();
            Sdk.registerNIM();
            Sdk.registerBaiDu();
            window.systemModel = CommonUtil.getSystemModel();
            //LocationUtil.init();
        }
    },

    _initNetworkListeners: function () {
        Board.prototype._initNetworkListeners.call(this);
        this._networkListeners = {
            Login: '_loginCallBack',
            // Offline: '_playerOffline',
            // RefreshPlayersLoc: '_refreshPlayersLocation',
            // GS_UserJoin_NiuNiu: '_onUserJoinNiuNiu',
            // GS_UserJoin: '_onUserJoin',
            GS_RoomInfo: '_reConnect',
            GS_UserJoin: '_onUserJoin',
            JoinRoom: '_joinRoom',
            ReContent: '_reConnect',
            SubUpdate: '_subUpdate',
            Speaker: '_onSpeaker'
        };
        /**
         * 全局监听3007
         */
        network.addListener(3007, function (data) {
            for (var uid in data['map']) {
                if (!data['map'].hasOwnProperty(uid)) {
                    continue;
                }
                var player = gameData.getPlayerInfoByUid(uid);
                if (player) {
                    player.loc = data['map'][uid].loc;
                    player.locCN = data['map'][uid].locCN;
                    player.locUpdTime = data['map'][uid].locUpdTime;
                }
            }
        });
    },

    _initClickListeners: function () {
        Board.prototype._initClickListeners.call(this);
        this._clickListeners = {
            'root.xieyi.image_xieyi': '_clickXieYi',
            'root.btn_xiufu': '_clickXiufu'
        };
    },

    _initEventListeners: function () {
        Board.prototype._initEventListeners.call(this);
        this._eventListeners[EventKey.DoLogin] = "_doLogin";
    },

    redirectLogin: function () {

    },

    /**
     * 点击修复
     * @private
     * */
    _clickXiufu: function () {
        showXiuFuWindow();
    },
    /**
     * 点击协议
     * @private
     */
    _clickXieYi: function () {
        cc.sys.openURL('https://www.yayayouxi.com/terms/gameTerms.html');
    },
    /**
     * 执行登录
     * @private
     */
    _doLogin: function () {
        this._retryTime = 0;
        this._ipList = this._getIplist();
        this._connectServer();
    },

    /**
     * 联接服务器
     * @private
     */
    _connectServer: function () {
        var self = this;
        if (this._retryTime > 0) {
            showLoading('正在进行第' + this._retryTime + '次尝试');
        }

        showLoading('正在连接服务器..');
        self._time2001 = getCurrentTimeMills();

        var ip = this._ipList[this._retryTime];
        // cc.log(this._ipList);
        // cc.log('ip = ' + ip);
        if (_.startsWith(ip, 'yxd:')) {
            var yxd = ip.substr(4);
            ip = this._getYunCengIp(yxd);

            if (ip && /\d+\.\d+\.\d+\.\d+/.test(ip)) {
            } else {
                self._retryTime++;
                self._connectServer();
                return;
            }

        }
        self.endpoint = ip;
        // cc.log('end_ip:' + self.endpoint);
        if (!cc.isUndefined(ip)) {
            network.connect(gameData.clientId, this._connectSuccess.bind(this), this._connectFailure.bind(this), ip);
        }
    },

    /**
     * 由于不同app ip列表应该不同，所以在这里处理
     * 初始化iplist
     * @protected
     */
    _getIplist: function () {
        // 先取存的ip
        // try {
        //     var saveIplist = cc.sys.localStorage.getItem('ipList');
        //     if (saveIplist) {
        //         saveIplist = JSON.parse(saveIplist);
        //         if (_.isArray(saveIplist) && saveIplist.length > 0) {
        //             return saveIplist;
        //         }
        //     }
        // } catch (e) {
        //     cc.error("读取存储的ip失败!");
        //     cc.sys.localStorage.removeItem('ipList');
        // }


        var ipList = [];
        //
        // // 1、游戏盾
        // if (!window.inReview && cc.sys.isNative) {
        //     // 1.1、游戏盾分组
        //     if (app.yxdGroup) {
        //         var playerLv = (cc.sys.localStorage.getItem('playerLv') || '00');
        //         var group0 = app.yxdGroup[playerLv] || app.yxdGroup['00'];
        //         if(group0){
        //             ipList.push('yxd:' + getDAes(group0));
        //         }
        //     }
        //
        //     var playero = (cc.sys.localStorage.getItem('playero') || '0');
        //     if (app.yxdBigGroup && playero != '0') {
        //         playero = Math.floor((playero / 86400)) % app.yxdBigGroup.length;
        //     }
        //
        //     // 1.2、游戏大分组1
        //     if (app.yxdBigGroup && app.yxdBigGroup[playero]) {
        //         var group1 = getDAes(app.yxdBigGroup[playero]);
        //         ipList.push('yxd:' + group1);
        //     }
        // }

        // 2、域名
        ipList.push(app.gameUrl);

        return ipList;
    },

    /**
     * 获取游戏盾IP
     * @param group_name
     * @returns {String}
     * @private
     */
    _getYunCengIp: function (group_name) {
        return DeviceUtil.getNextIPByGroup(this._getYunCengKey(), group_name);
    },

    /**
     * 获取游戏盾Key
     * @returns {string}
     * @private
     */
    _getYunCengKey: function () {
        if (cc.sys.os === cc.sys.OS_IOS) {
            return YunCengKey_ios_532;
        } else if (cc.sys.os === cc.sys.OS_ANDROID) {
            return YunCengKey_android_ver3;
        }
        return '';
    },

    /**
     * 联接成功
     * @private
     */
    _connectSuccess: function () {
        var self = this;
        var data = {
            last_retry: this._retryTime,
            openid: gameData.clientId,
            nickname: gameData.nickname,
            sex: gameData.sex,
            province: gameData.province,
            city: gameData.city,
            country: gameData.country,
            headimgurl: gameData.headimgurl,
            unionid: gameData.unionid,
            version: window.curVersion,
            nativeVersion: window.nativeVersion,
            isnative: (cc.sys.isNative ? 1 : 0),
            os: cc.sys.os,
            needComp: true,
            endpoint: self.endpoint,
            systemModel:CommonUtil.getSystemModel(),
            systemVersion:CommonUtil.getSystemVersion(),
            connectTime: (getCurrentTimeMills() - self._time2001) / 1000
        };
        showLoading('正在发送登录请求');
        network.send(MsgCode.Login, data);
    }
    ,
    /**
     * 联接失败
     * @private
     */
    _connectFailure: function () {
        this._retryTime++;
        if (this._retryTime >= this._ipList.length) {
            this._retryTime = 0;
            hideLoading();
            cc.sys.localStorage.removeItem('ipList');
            showAlert('网络访问失败，请检查网络');
            return;
        }
        this._connectServer();
    },

    /**
     * 2001
     * 登录回调
     * @private
     */
    _loginCallBack: function (data) {
        gameData.area = app.area;
        gameData.appId = app.appId;
        gameData.opt_conf = data['opt_conf'] || {};
        gameData.opt_conf_2 = data['opt_conf_2'] || {};

        gameData.useNewClub = true; // 混合牌桌使用字段,目前仅有 快乐麻将使用
        gameData.BDIphone = data['userDetail'] ? (data['userDetail']['mobile'] ? data['userDetail']['mobile'] : "") : "";
        if (data['server_address']) {
            // saveIpLists(data['server_address']);
        }
        gameData.hasLogined = true;
        gameData.uid = data.uid;
        gameData.numOfCards = data['numof_cards'];
        gameData.cardnum = gameData.numOfCards[1];
        gameData.diamondnum = gameData.numOfCards[2];
        gameData.coinnum = gameData.numOfCards[0];
        gameData.ip = data['ip'];
        gameData.isNew = data['is_new'];
        gameData.weixin = decodeURIComponent(data['weixin']);
        gameData.weixin2 = decodeURIComponent(data['weixin2']);
        gameData.triggers = data['triggers'] || [];
        gameData.map_conf = data['map_conf'] || {};
        gameData.refer = data['refer'];
        gameData.hasShiMing = data['hasShiMing'];
        gameData.o = data['create_time'] || '0';
        gameData.link = gameData.opt_conf['link'];
        gameData.parent_id = data['parent_id'];
        gameData.location = data['loc'];
        gameData.locationInfo = data['locCN'];
        if (gameData.locationInfo == undefined && data['locCN_Base64']) {
            gameData.locationInfo = data['locCN_Base64'];
        }
        //热门游戏标签
        gameData.HotList = gameData.opt_conf_2.HotList;
        gameData.jubao = data['jubao'] || 0;
        // app.shareDownLoadUrl = gameData.opt_conf_2.shareDownLoadUrl || app.shareDownLoadUrl;
        // app.room_link = gameData.opt_conf_2.roomUrl || '';
        // app.club_link = gameData.opt_conf_2.clubUrl || '';
        //
        // app.MWUrl = gameData.opt_conf_2.MWUrl || app.MWUrl;
        // if(app.MWUrl){
        //     if (gameData.link == 1) {
        //         app.shareUrl = app.shareDownLoadUrl;
        //         app.shareClubUrl = app.shareDownLoadUrl;
        //     } else if (gameData.link == 2) {
        //         if(app.room_link){
        //             app.shareUrl = app.room_link + app.MWUrl;
        //         }else{
        //             app.shareUrl = app.MWUrl;
        //         }
        //         if(app.club_link){
        //             app.shareClubUrl = app.club_link + app.MWUrl;
        //         }else{
        //             app.shareClubUrl = app.MWUrl;
        //         }
        //     } else {
        //         app.shareUrl = app.MWUrl;
        //         app.shareClubUrl = app.MWUrl;
        //     }
        // }else{
        //     app.shareUrl = app.shareDownLoadUrl;
        //     app.shareClubUrl = app.shareDownLoadUrl;
        // }
        //春节活动
        app.shareUrl = app.room_link + app.MWUrl;
        app.shareClubUrl = app.club_link + app.MWUrl;
        gameData.newyear = gameData.opt_conf.newyear || false;
        gameData.ts = (data['ts'] || '000') + '';
        if (gameData.ts && gameData.ts.length > 3) {
            var ts = gameData.ts[gameData.ts.length - 4];
            var deci = gameData.ts[gameData.ts.length - 5];
            if (parseInt(deci) % 2 == 0) {
                deci = 0;
            } else {
                deci = 1;
            }
            if ((ts == '8' || ts == '9') && deci == 1) {
                ts = parseInt(Math.random() * 7);
            }
            cc.sys.localStorage.setItem('playerLv', '' + deci + ts);
        }
        cc.sys.localStorage.setItem('playero', gameData.o);
        LocationUtil.startRefreshAddress();

        /**
         * 通用功能
         */
        // ItemData.loadAllProto();
        //金币场
        // if (data['jbUserDetail']) {
        //     gameData.jbcData = data['jbUserDetail'];     //ps 添加金币场后，修改金币数据来源 
        //     gameData.gid = gameData.jbcData['_id'] || 0;
        //     if (gameData.numOfCards) {
        //         gameData.numOfCards[0] = gameData.jbcData.jbNum || 0;
        //     }
        //     cc.log('jbUserDetail = ' + JSON.stringify(gameData.jbcData) || 'undefine');
        // }
        //比赛场
        gameData.isLunKong = data['isInMatch'] || 0;//是否比赛轮空状态
        gameData.isOpenMatch = (gameData.uid % 100 < (gameData.opt_conf_2['ShowMatch'] || 0));
        var ShowMatchUids = gameData.opt_conf_2['ShowMatchUids'];
        if(ShowMatchUids){
            gameData.ShowMatchUids = ShowMatchUids.split(',');
            if (_.isArray(gameData.ShowMatchUids) && gameData.ShowMatchUids.length > 0) {
                for (var k = 0; k < gameData.ShowMatchUids.length; k++) {
                    if(gameData.uid == gameData.ShowMatchUids[k]){
                        gameData.isOpenMatch = true;
                    }
                }
            }
        }
        /**
         * 俱乐部监听
         */
        // club.ClubManager.getInstance();
        var isReconnect = data['is_reconnect'];
        if (!isReconnect) {
            if(gameData.returnClubId){
                showBoard('ClubBoard', gameData.returnClubId);
            }else {
                showBoard('HallBoard');
            }

        }
    },

    /**
     * 加入房间
     * @param {String} data
     * @param {Number} errorCode
     * @private
     */
    _joinRoom: function (data, errorCode) {
        if (errorCode) {
            var errorMsg = null;
            if (errorCode == -20) errorMsg = '房间号不存在, 请重新输入';
            if (errorCode == -30) errorMsg = '该房间已满员, 无法加入';
            if (errorCode == -60) errorMsg = '该房间已开始, 无法加入';
            if (errorCode == -40) errorMsg = '您的房卡不足';
            if (errorCode == -2) errorMsg = '版本过低。请退出后重新登陆';
            if (data && data.errorMsg) {
                errorMsg = data.errorMsg;
            }
            showBoard('HallBoard');
            showAlert(errorMsg);
            // HUD.showScene(HUD_LIST.Home);
            return;
        }
        SubUpdateUtil.showGameScene(data, ROOM_DATA_TYPE.CREATE);
    },
    /**
     * 胡子加入房间
     * @param data
     * @private
     */
    _onUserJoin: function (data) {
        var Result = null;
        if (data.Head) {
            Result = data.Head.Result;
        }
        if (data.Result != null) {
            Result = data.Result;
        }
        if (Result == 0) {
            SubUpdateUtil.showGameScene(data, ROOM_DATA_TYPE.CREATE);
        } else {
            hideLoading();
            if (data.Head) {
                showMessageBox(data.Head.ErrorMsg);
            } else {
                showMessageBox(data.ErrorMsg);
            }
        }
    },
    /**
     * 断线重连
     * @private
     */
    _reConnect: function (data) {
        SubUpdateUtil.showGameScene(data, ROOM_DATA_TYPE.RECONNECT);
    },

    /**
     * 是否同意了协议
     * @returns {Boolean}
     * @public
     */
    agreeXieYi: function () {
        return this._nodeList['root.xieyi.cbBox'].isSelected();
    },
    /**
     * 模块更新
     * @private
     */
    _subUpdate: function (data) {
        SubUpdateUtil.subUpdate(data);
    },

    /**
     * 存储跑马灯数据
     * @param data
     * @private
     */
    _onSpeaker: function (data) {
        window['mainlayer_3200_data'] = data.content;
    }
});